// Copyright 2010 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.android.apps.moderator;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;

/**
 * This activity exists in order to direct URLs formatted for the main website to the appropriate
 * activity in Moderator for Android.
 *
 * <P>E.g. Topic URLs look like this: http://www.google.com/moderator/#15/e=5120&t=5120.40
 */
public class MainUrlActivity extends Activity {

  /**
   * Hunts for the e=(some hex number) parameter in a Moderator URL
   */
  private static final Pattern seriesPattern = Pattern.compile("(e=)(.[a-zA-Z0-9]*)");

  /**
   * Hunts for the t=(series).(some hex number) parameter in a Moderator URL
   */
  private static final Pattern topicPattern = Pattern.compile("(t=[^\\.]+\\.)(.[a-zA-Z0-9]*)");

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    Intent intent = getIntent();
    Matcher seriesMatcher = seriesPattern.matcher(intent.getDataString());
    if (seriesMatcher.find()) {
      Intent newIntent;
      Matcher topicMatcher = topicPattern.matcher(intent.getDataString());
      if (topicMatcher.find()) {
        // If a topic parameter is found, this URL refers to a Topic
        newIntent = new Intent(this, TopicActivity.class);
        // Parameters are converted from hex and passed in a more friendly form
        newIntent.putExtra("topicId",  Integer.parseInt(topicMatcher.group(2), 16));
      } else {
        // This URL refers to a Series
        newIntent = new Intent(this, SeriesActivity.class);
      }
      // Parameters are converted from hex and passed in a more friendly form
      newIntent.putExtra("seriesId", Integer.parseInt(seriesMatcher.group(2), 16));
      startActivity(newIntent);
    }
    super.onCreate(savedInstanceState);
  }
}
